const express = require('express')
const app = express()
const { getIP, createLog, spawnChild } = require('./utils')

const log = createLog('app')

let isBuilding = false
let isMerging = false
let currentUser = ''

app.use(express.urlencoded({extended: true}))
app.use(express.json())
app.use(express.static('public'))

app.get('/hi', (req, res) => {
  console.log('req.headers==================>::', req.headers)
  res.set('content-type', 'text/plain')
  res.end('hello' + Date.now())
})

function buildingTips() {
  return `<div class=warning-tips><em> ${currentUser} </em> 正在构建中，请稍候...`
}
function mergingTips() {
  return `<div class=warning-tips><em> ${currentUser} </em> 正在合并中，请稍候...`
}

app.post('/merge', (req, res) => {
  console.log('req.query', req.query)
  console.log('req.body', req.body)
  let { nickname, branch } = req.body
  if (!branch || !(branch + '').trim()) {
    branch = 'noneed'
  }


  if (isBuilding) {
    res.write(buildingTips())
    spawnChild('bash', ['./scripts/log.sh'], data => res.write(data), data => { res.write(data); res.end()})
    return
  }

  if (isMerging) {
    res.write(mergingTips())
    spawnChild('bash', ['./scripts/log.sh'], data => res.write(data), data => { res.write(data); res.end()})
    return
  }

  isMerging = true
  currentUser = nickname
  res.setHeader('content-type', 'text/html; charset=utf-8')

  const dataCb = (data) => {
    res.write(data)
  }

  const doneCb = (data) => {
    res.write(data)
    res.end()
    isMerging = false
  }

  // spawnChild('ping', ['-n', '10', 'www.baidu.com'], dataCb, doneCb)
  spawnChild('bash', ['./scripts/merge.sh', branch, nickname], dataCb, doneCb)

  // res.end('new day')
})

app.post('/build', (req, res) => {
  log('req.query', req.query)
  log('req.body', req.body)
  let { nickname, branch } = req.body
  if (!branch || !(branch + '').trim()) {
    branch = 'noneed'
  }

  if (isBuilding) {
    res.write(buildingTips())
    spawnChild('bash', ['./scripts/log.sh'], data => res.write(data), data => { res.write(data); res.end()})
    return
  }

  
  if (isMerging) {
    res.write(mergingTips())
    spawnChild('bash', ['./scripts/log.sh'], data => res.write(data), data => { res.write(data); res.end()})
    // res.end()
    return
  }

  isBuilding = true
  currentUser = nickname
  res.setHeader('content-type', 'text/html; charset=utf-8')

  const dataCb = (data) => {
    res.write(data)
  }

  const doneCb = (data) => {
    res.write(data)
    res.end()
    isBuilding = false
  }

  // spawnChild('ping', ['-n', '10', 'www.baidu.com'], dataCb, doneCb)
  spawnChild('bash', [req.query.prod ? './scripts/build-prod.sh' : './scripts/build.sh', branch, nickname], dataCb, doneCb)

  // res.end('new day')
})
app.use((req, res, next) => {
  console.log('cors middleware: ', req.url)
  res.set('Access-Control-Allow-Origin', 'http://localhost:9527')
  res.set('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT,HEAD')
  res.set('Access-Control-Allow-Headers', 'X-KK,Content-Type,Content-Length,Cache-Control,Date,authorization')
  next()
})
app.get('/mytest', (req, res, next) => {
  console.log('===============test:', req.url)
  // res.set('Content-Type', 'application/json')
  res.set('Access-Control-Allow-Origin', 'http://localhost:9527')
  res.set('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT,HEAD')
  res.set('Access-Control-Allow-Headers', 'X-KK,Content-Type,Content-Length,Cache-Control,Date,authorization')
  res.set('Access-Control-Expose-Headers', 'X-KK,Content-Type,Content-Length,Cache-Control,Date,authorization')
  res.set('X-KK', 'yes')
  res.set('foo', 'foolish')
  res.set('bar', 'black')
  res.send({code: 10000, msg: 'good'})
  res.end()
})

app.listen(3000, () => {
  console.log(`server in running at  http://${getIP()}:3000`);
})